<?php
// Connect to the database
$host = "mysql";
$username = "root";
$password = "123456";
$dbname = "todo";
$conn = mysqli_connect($host, $username, $password, $dbname);
$text = "";
// Check the request method
switch ($_SERVER["REQUEST_METHOD"]) {
  case "POST":
    // Add a new todo item
    //$text = mysqli_real_escape_string($conn, $_POST["text"]);
    $post_j = file_get_contents("php://input");
    $post = json_decode($post_j,true);
    $text = $post['text'];
    $sql = "INSERT INTO items (text) VALUES ('$text')";
    mysqli_query($conn, $sql);
    break;
  case "DELETE":
    // Delete a todo item
//     $text = mysqli_real_escape_string($conn, $_POST["text"]);
    $post_j = file_get_contents("php://input");
    $post = json_decode($post_j,true);
    $text = $post['text'];
    $sql = "DELETE FROM items WHERE text='$text'";
    mysqli_query($conn, $sql);
    break;
    case "UPDATE":
        // Delete a todo item
    //     $text = mysqli_real_escape_string($conn, $_POST["text"]);
        $post_j = file_get_contents("php://input");
        $post = json_decode($post_j,true);
        $text = $post['text'];
        $sql = "UPDATE items SET completed = 1 WHERE text='$text'";
        mysqli_query($conn, $sql);
        break;
    default:
       break;
}

// Get the list of all todo items from the database
$sql = "SELECT * FROM items";
$result = mysqli_query($conn, $sql);
$items = mysqli_fetch_all($result, MYSQLI_ASSOC);

// Close the connection
mysqli_close($conn);

// Convert the list of todo items to JSON and send it back to the client
echo json_encode($items);
